package com.ruoyi.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageList;
import com.ruoyi.system.domain.SearchResult;
import com.ruoyi.system.domain.SysArticle;
import com.ruoyi.system.service.ISolrService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.TextUtils;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @PackageName com.ruoyi.system.service.impl
 * @ClassName SolrServiceImpl
 * @Auther jgg
 * @Date 2022-7-20 17:58
 */
@Service
@Slf4j
public class SolrServiceImpl implements ISolrService {

    @Autowired
    private SolrClient solrClient;


    @Override
    public AjaxResult searchArticle(Integer pageNo, Integer pageSize, Map<String, Object> params) {
        /** 获取参数*/
        String keyword = (String) params.get("keyword");
        String categoryId = (String) params.get("categoryId");
        String sort = (String) params.get("sort");
        SolrQuery solrQuery = new SolrQuery();
        //分页设置
        //设置每页分页的数量
        solrQuery.setRows(pageSize);
        //设置起始位置
        int start = (pageNo - 1) * pageSize;
        solrQuery.setStart(start);
        //3、设置搜索条件
        //关键字
        solrQuery.set("df", "search_item");
        //条件过滤
        if (TextUtils.isEmpty(keyword)) {
            //该行为会导致魔鬼搜索，进行全表扫描较为耗费资源
            solrQuery.set("q", "*");
        } else {
            solrQuery.set("q", keyword);
        }
        /*排序*/
        //根据时间升级
        if (sort != null) {
            if (sort == "1") {
                solrQuery.setSort("blog_create_time", SolrQuery.ORDER.asc);
            } else if (sort == "2") {
                solrQuery.setSort("blog_create_time", SolrQuery.ORDER.desc);
            } else if (sort == "3") {
                solrQuery.setSort("blog_view_count", SolrQuery.ORDER.asc);
            } else if (sort == "4") {
                solrQuery.setSort("blog_view_count", SolrQuery.ORDER.desc);
            }
        }
        //分类
        if (StrUtil.isNotEmpty(categoryId)) {
            solrQuery.setFilterQueries("blog_category_id:" + categoryId);
        }
        //关键字高亮
        solrQuery.setHighlight(true);
        solrQuery.addHighlightField("blog_title");
        solrQuery.setHighlightSimplePre("<font color='red'>");
        solrQuery.setHighlightSimplePost("</font>");
        solrQuery.setHighlightFragsize(500);

        //设置返回字段
        solrQuery.addField("id,blog_create_time,blog_labels,blog_url,blog_title,blog_summary,blog_view_count,blog_cover");
        //
        //4、搜索
        try {
            //4.1、处理搜索结果
            QueryResponse result = solrClient.query(solrQuery);
            //获取到高亮内容
            Map<String, Map<String, List<String>>> highlighting = result.getHighlighting();
            //把数据转成bean类
            List<SearchResult> resultList = result.getBeans(SearchResult.class);
            //结果列表
            for (SearchResult item : resultList) {
                Map<String, List<String>> stringListMap = highlighting.get(item.getId());
                if (stringListMap == null) {
                    //到下一个循环
                    continue;
                }
                //List<String> blogContent = stringListMap.get("blog_content");
                //if (blogContent != null) {
                //    item.setBlogContent(blogContent.get(0));
                //}
                List<String> blogTitle = stringListMap.get("blog_title");
                if (blogTitle != null) {
                    item.setBlogTitle(blogTitle.get(0));
                }
            }
            //5、返回搜索结果
            //包含内容
            //列表、页面、每页数量
            long numFound = result.getResults().getNumFound();
            PageList<SearchResult> pageList = new PageList<>(pageNo, numFound, pageSize);
            pageList.setContents(resultList);
            //返回结果
            return AjaxResult.success(pageList);
            //返回结果
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 添加文章
     *
     * @param article
     */
    @Override
    public void addArticle(SysArticle article) {
        SolrInputDocument doc = new SolrInputDocument();
        doc.addField("id", article.getId());
        doc.addField("blog_view_count", article.getViewCount());
        doc.addField("blog_title", article.getTitle());
        String type = article.getType();
        //String html;
        //if (Constants.article.TYPE_MARKDOWN.equals(type)) {
        //    //markdown to html
        //    MutableDataSet options = new MutableDataSet().set(Parser.EXTENSIONS, Arrays.asList(
        //            TablesExtension.create(),
        //            JekyllTagExtension.create(),
        //            TocExtension.create(),
        //            SimTocExtension.create()
        //    ));
        //    Parser parser = Parser.builder(options).build();
        //    HtmlRenderer renderer = HtmlRenderer.builder(options).build();
        //
        //    Node document = parser.parse(article.getContent());
        //    html = renderer.render(document);
        //}else {
        //    html= article.getContent();
        //}
        //String content = Jsoup.parse(html).text();
        //doc.addField("blog_content",content);
        //存放摘要
        doc.addField("blog_summary", article.getSummary());
        doc.addField("blog_cover", article.getCover());
        doc.addField("blog_create_time", DateUtils.getNowDate());
        doc.addField("blog_labels", article.getLabels());
        doc.addField("blog_url", "/article/" + article.getId());
        doc.addField("blog_category_id", article.getCategoryId());
        try {
            solrClient.add(doc);
            solrClient.commit();
        } catch (SolrServerException | IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 更新文章
     *
     * @param sysArticle
     */
    @Override
    public void updateArticle(SysArticle sysArticle) {
        this.addArticle(sysArticle);
    }

    /**
     * 删除文章
     *
     * @param articleId
     */
    @Override
    public void deleteArticle(Long articleId) {
        try {
            solrClient.deleteById(String.valueOf(articleId));
            solrClient.commit();
        } catch (SolrServerException e) {
            e.printStackTrace();
            log.info("solr删除数据失败:文章id为{}  =======》", articleId);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) {
        Map<String, Object> params = new HashMap<>();
        params.put("categoryId", "123");
        params.put("keyword", "测试");
        Integer sort = (Integer) params.get("sort");
        System.out.println("sort = " + sort);
    }
}
